import base64
import pickle
from django_redis import get_redis_connection

def merge_cart_cookie_to_redis(request, user, response):
    cookie_dict = request.COOKIE.get('carts')
    if not cookie_dict:
        return response
    cart_dict = pickle.loads(base64.b64decode(cookie_dict.encode()))

    new_dict = {}
    new_add = []
    new_remove = []

    for user_id, item in cart_dict:
        new_dict[user_id] = item['count']

        if item['selected']:
            new_add.append(user_id)
        else:
            new_remove.append(user_id)

    redis_conn = get_redis_connection('carts')
    pl = redis_conn.pipeline()
    pl.hmset('cart_%s' % user.id, new_dict)
    if new_add:
        pl.sadd('selected_%s' % user.id, *new_add)
    if new_remove:
        pl.srem('selected_%s' % user.id, *new_remove)
    pl.execute()

    response.delete_cookie('carts')

    return response